<template>
  <div class="min-h-screen bg-white flex justify-center">
    <!-- 使用导航栏组件 -->
    <!-- <NavHeader title="流通" /> -->
    <div class="w-full md:max-w-[800px] p-4 pb-20 pt-[80px]">
      
      <!-- HDFS Balance Card -->
      <div class="mb-6 border-none shadow-md overflow-hidden rounded-lg">
        <div class="bg-gradient-to-r from-blue-600 to-blue-400 p-6 text-white">
          <div class="flex items-center justify-between mb-2">
            <h2 class="text-lg font-medium">HDFS余额</h2>
            <van-icon name="balance-o" class="h-5 w-5" />
          </div>
          <div class="text-3xl font-bold mb-1">{{ hdfsBalance.balance ? formatNumber(hdfsBalance.balance) : '0' }}</div>
          <div class="flex justify-between text-sm opacity-90">
            <div class="flex items-center">
              <van-icon name="arrow" class="h-4 w-4 mr-1 text-green-300 rotate-45" />
              <span>收入: {{ hdfsBalance.totalIn ? formatNumber(hdfsBalance.totalIn) : '0' }}</span>
            </div>
            <div class="flex items-center">
              <van-icon name="arrow" class="h-4 w-4 mr-1 text-red-300 -rotate-45" />
              <span>支出: {{ hdfsBalance.totalOut ? formatNumber(hdfsBalance.totalOut) : '0' }}</span>
            </div>
          </div>
        </div>
        <div class="p-4 bg-white">
          <div class="flex justify-between items-center">
            <div class="cursor-pointer flex items-center text-blue-600" @click="goToTransactions">
              <span>贡献记录</span>
              <van-icon name="arrow" class="h-4 w-4 ml-1" />
            </div>
            <van-button 
              type="primary"
              class="custom-button"
              @click="goToPointsExchange"
            >
              积分兑换
            </van-button>
          </div>
        </div>
      </div>
      
        <!-- Currency Exchange Section -->
      <div class="mb-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-lg font-bold">币种兑换</h2>
          <div class="text-blue-600 text-sm flex items-center cursor-pointer" @click="navigateTo('/currency-exchange')">
            查看全部
            <van-icon name="arrow" class="h-4 w-4 ml-1" />
          </div>
        </div>
        
        <!-- 动态渲染币种兑换卡片 -->
        <div 
          v-for="currency in currencies" 
          :key="currency.id"
          class="mb-4 last:mb-0 border-none shadow-sm cursor-pointer hover:shadow-md transition-shadow bg-white rounded-lg"
          @click="goToCurrencyExchange(currency.icon)"
        >
          <div class="p-4">
            <div class="flex justify-between items-center mb-3">
              <div class="flex items-center">
                <div class="ml-4">
                  <div class="font-semibold">HDFS → {{ currency.name }}</div>
                  <div class="text-sm text-slate-500">昨日比例：1 HDFS = {{ currency.rate }} {{ currency.name }}</div>
                </div>
              </div>
              <van-button 
                size="small" 
                type="primary"
                class="custom-button"
                @click.stop="goToCurrencyExchange(currency.icon)"
              >
                立即兑换
              </van-button>
            </div>
            <div class="flex justify-between text-xs text-slate-500">
              <div>截止时间: {{ currency.deadline }}</div>
              <div>预计打款时间: {{ currency.paymentTime ? 'T+'+currency.paymentTime : 'T+1'}}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Circulation Statistics Section -->
      <div>
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-lg font-bold">数据流通统计</h2>
        </div>
        
        <!-- Statistics Cards -->
        <div class="grid grid-cols-3 gap-3 mb-4">
          <div class="border-none shadow-sm bg-white rounded-lg">
            <div class="p-3 flex flex-col items-center">
              <van-icon name="bar-chart-o" class="h-5 w-5 text-blue-600 mb-1" />
              <div class="text-xs text-slate-500">累计流通量</div>
              <div class="font-bold text-lg">{{ stats.totalCirculation ? formatNumber(stats.totalCirculation) : '0' }}</div>
            </div>
          </div>
          
          <div class="border-none shadow-sm bg-white rounded-lg">
            <div class="p-3 flex flex-col items-center">
              <van-icon name="friends-o" class="h-5 w-5 text-blue-600 mb-1" />
              <div class="text-xs text-slate-500">参与人数</div>
              <div class="font-bold text-lg">{{ stats.participants ? formatNumber(stats.participants) : '0' }}</div>
            </div>
          </div>
          
          <div class="border-none shadow-sm bg-white rounded-lg">
            <div class="p-3 flex flex-col items-center">
              <van-icon name="calendar-o" class="h-5 w-5 text-blue-600 mb-1" />
              <div class="text-xs text-slate-500">今日流通量</div>
              <div class="font-bold text-lg">{{ stats.todayCirculation ? formatNumber(stats.todayCirculation) : '0' }}</div>
            </div>
          </div>
        </div>
        
        <!-- 7-Day Trend Chart with ECharts -->
        <div class="border-none shadow-lg bg-white rounded-lg overflow-hidden">
          <div class="p-5">
            <div class="flex justify-between items-center mb-6">
              <div class="font-medium text-base">7天流通走势</div>
              <div class="flex items-center">
                <div class="w-3 h-3 bg-gradient-to-r from-blue-600 to-blue-400 rounded-sm mr-2"></div>
                <span class="text-xs text-slate-500">HDFS流通量</span>
              </div>
            </div>
            
            <!-- ECharts容器 -->
            <div ref="chartContainer" class="h-60 w-full"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { showLoadingToast } from 'vant'
import NavHeader from '@/components/NavHeader.vue'
import { getExchangeCurrencies, getCirculationStats, getWeeklyTrend } from '@/api/circulation'
import { getUserWallet } from '@/api/user'
import * as echarts from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import { 
  TitleComponent, 
  TooltipComponent, 
  GridComponent, 
  LegendComponent,
  DataZoomComponent 
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  TitleComponent, 
  TooltipComponent, 
  GridComponent, 
  LegendComponent,
  DataZoomComponent,
  BarChart,
  LineChart,
  CanvasRenderer
])

const router = useRouter()
const chartContainer = ref(null)
let chart = null

// 数据状态
const hdfsBalance = ref({
  balance: 0,
  totalIn: 0,
  totalOut: 0
})

const currencies = ref([])
const stats = ref({
  totalCirculation: 0,
  participants: 0,
  todayCirculation: 0
})

// 趋势图数据
const trendData = ref({
  dates: [],
  values: []
})


// 初始化图表
const initChart = () => {
  if (!chartContainer.value) {
    //console.error('图表容器不存在')
    return
  }
  
  // 如果已经有图表实例，先销毁
  if (chart) {
    chart.dispose()
  }
  
  // 创建图表实例
  chart = echarts.init(chartContainer.value)
  
  // 准备数据
  const dates = trendData.value.dates || []
  const values = trendData.value.values || []
  
  // 格式化日期
  const formattedDates = dates.map(date => {
    const d = new Date(date)
    return `${d.getMonth() + 1}月${d.getDate()}日`
  })
  
  //console.log('图表数据:', { dates: formattedDates, values })
  
  // 设置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const date = params[0].name
        const value = formatNumber(params[0].value)
        return `<div style="font-weight:bold;margin-bottom:5px">${date}</div>
                <div style="display:flex;align-items:center;margin:3px 0">
                  <span style="display:inline-block;width:10px;height:10px;background:#3b82f6;border-radius:50%;margin-right:5px"></span>
                  <span>HDFS流通量: ${value} HDFS</span>
                </div>`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: formattedDates,
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: 'HDFS流通量',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#3b82f6'
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: 'HDFS流通量',
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#60a5fa' },
            { offset: 1, color: '#3b82f6' }
          ])
        },
        data: values
      }
    ]
  }
  
  // 设置图表
  chart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chart && chart.resize()
  })
}

// 加载数据
const loadData = async () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  
  try {
  
    // 1. 获取HDFS余额数据
    try {
      const balanceRes = await getUserWallet({ icon: 'HDFS' });
      if (balanceRes.code === 0 && balanceRes.data && balanceRes.data.length > 0) {
        hdfsBalance.value = balanceRes.data[0];
      }
    } catch (error) {
      console.error('获取HDFS余额失败:', error);
    }
    
    // 2. 获取币种兑换数据(主要是价格等)
    try {
      const currenciesRes = await getExchangeCurrencies();
      if (currenciesRes.code === 0 && currenciesRes.data) {
        currencies.value = currenciesRes.data;
        currencies.value.color = "green"
      }
    } catch (error) {
      console.error('获取币种兑换数据失败:', error);
    }
    
    // 3. 获取流通统计数据
    try {
      const statsRes = await getCirculationStats();
      if (statsRes.code === 0 && statsRes.data) {
        stats.value = statsRes.data;
      }
    } catch (error) {
      console.error('获取流通统计数据失败:', error);
    }
    
    // 4. 获取趋势图数据
    try {
      const trendRes = await getWeeklyTrend();
      if (trendRes.code === 0 && trendRes.data) {
        trendData.value = trendRes.data;
        
        // 初始化图表
        nextTick(() => {
          if (chartContainer.value) {
            chartContainer.value.style.height = '240px';
            initChart();
          }
        });
      }
    } catch (error) {
      console.error('获取趋势图数据失败:', error);
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    showLoadingToast().close()
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadData()
})

// 组件卸载时销毁图表
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  
  window.removeEventListener('resize', () => {
    chart && chart.resize()
  })
})

const goToPointsExchange = () => {
  router.push('/circulation/points-exchange')
}

const goToCurrencyExchange = (currency) => {
  router.push({
    path: '/circulation/exchange',
    query: { currency }
  })
}

const goToTransactions = () => {
  router.push('/circulation/points-record')
}

const navigateTo = (path) => {
  if (path === '/currency-exchange') {
    router.push('/circulation/exchange')
  } else {
    router.push(path)
  }
}

// 格式化数字，去掉小数点末尾的0
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0';
  
  // 先使用toLocaleString格式化数字（添加千位分隔符）
  let formattedNum = num.toLocaleString();
  
  // 如果包含小数点
  if (formattedNum.includes('.')) {
    // 去掉末尾的0
    formattedNum = formattedNum.replace(/\.?0+$/, '');
  }
  
  return formattedNum;
}
</script>

<style scoped>
/* Base styles */
.min-h-screen {
  min-height: 100vh;
}

.bg-white {
  background-color: #ffffff;
}

.flex {
  display: flex;
}

.justify-center {
  justify-content: center;
}

.w-full {
  width: 100%;
}

.md\:max-w-\[800px\] {
  max-width: 800px;
}

.p-4 {
  padding: 1rem;
}

.pb-20 {
  padding-bottom: 5rem;
}

.text-2xl {
  font-size: 1.5rem;
}

.font-bold {
  font-weight: 700;
}

.mb-6 {
  margin-bottom: 1.5rem;
}

/* Card styles */
.shadow-md {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.shadow-sm {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

.overflow-hidden {
  overflow: hidden;
}

.rounded-lg {
  border-radius: 0.5rem;
}

/* Gradient background */
.bg-gradient-to-r {
  background-image: linear-gradient(to right, var(--tw-gradient-stops));
}

.from-blue-600 {
  --tw-gradient-from: #2563eb;
  --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(37, 99, 235, 0));
}

.to-blue-400 {
  --tw-gradient-to: #60a5fa;
}

/* Text styles */
.text-white {
  color: #ffffff;
}

.text-lg {
  font-size: 1.125rem;
}

.font-medium {
  font-weight: 500;
}

.text-3xl {
  font-size: 1.875rem;
}

.text-sm {
  font-size: 0.875rem;
}

.opacity-90 {
  opacity: 0.9;
}

.text-blue-600 {
  color: #2563eb;
}

.text-green-300 {
  color: #86efac;
}

.text-red-300 {
  color: #fca5a5;
}

.text-slate-500 {
  color: #64748b;
}

.text-xs {
  font-size: 0.75rem;
}

/* Layout styles */
.flex-col {
  flex-direction: column;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.mb-1 {
  margin-bottom: 0.25rem;
}

.mb-2 {
  margin-bottom: 0.5rem;
}

.mb-3 {
  margin-bottom: 0.75rem;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mr-1 {
  margin-right: 0.25rem;
}

.ml-1 {
  margin-left: 0.25rem;
}

.ml-3 {
  margin-left: 0.75rem;
}

.p-3 {
  padding: 0.75rem;
}

.p-6 {
  padding: 1.5rem;
}

/* Grid styles */
.grid {
  display: grid;
}

.grid-cols-3 {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

.gap-3 {
  gap: 0.75rem;
}

/* Button styles */
.custom-button {
  background-color: #2563eb !important;
  border-color: #2563eb !important;
  color: white !important;
  border-radius: 0.25rem !important;
  font-weight: 500 !important;
}

.cursor-pointer {
  cursor: pointer;
}

.hover\:shadow-md:hover {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.transition-shadow {
  transition-property: box-shadow;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 150ms;
}

/* Chart styles */
.h-40 {
  height: 10rem;
}

.relative {
  position: relative;
}

.absolute {
  position: absolute;
}

.inset-0 {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.left-0 {
  left: 0;
}

.top-0 {
  top: 0;
}

.left-8 {
  left: 2rem;
}

.right-0 {
  right: 0;
}

.grid-rows-3 {
  grid-template-rows: repeat(3, minmax(0, 1fr));
}

.gap-0 {
  gap: 0;
}

.border-b {
  border-bottom-width: 1px;
}

.border-slate-200 {
  border-color: #e2e8f0;
}

.items-end {
  align-items: flex-end;
}

.px-2 {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}

.w-6 {
  width: 1.5rem;
}

.bg-blue-500 {
  background-color: #3b82f6;
}

.rounded-t-sm {
  border-top-left-radius: 0.125rem;
  border-top-right-radius: 0.125rem;
}

.group-hover\:bg-blue-600:hover {
  background-color: #2563eb;
}

.mt-1 {
  margin-top: 0.25rem;
}

.bottom-full {
  bottom: 100%;
}

.mb-2 {
  margin-bottom: 0.5rem;
}

.bg-slate-800 {
  background-color: #1e293b;
}

.py-1 {
  padding-top: 0.25rem;
  padding-bottom: 0.25rem;
}

.px-2 {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}

.rounded {
  border-radius: 0.25rem;
}

.opacity-0 {
  opacity: 0;
}

.group-hover\:opacity-100:hover {
  opacity: 1;
}

.transition-opacity {
  transition-property: opacity;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 150ms;
}

.pointer-events-none {
  pointer-events: none;
}

.whitespace-nowrap {
  white-space: nowrap;
}

/* Icon styles */
.h-5 {
  height: 1.25rem;
}

.w-5 {
  width: 1.25rem;
}

.h-4 {
  height: 1rem;
}

.w-4 {
  width: 1rem;
}

.w-10 {
  width: 2.5rem;
}

.h-10 {
  height: 2.5rem;
}

.rounded-full {
  border-radius: 9999px;
}

.bg-green-500 {
  background-color: #22c55e;
}

.bg-purple-500 {
  background-color: #a855f7;
}

.bg-orange-500 {
  background-color: #f97316;
}

.font-semibold {
  font-weight: 600;
}

/* Rotate arrow icons for trending up/down */
.rotate-45 {
  transform: rotate(45deg);
}

.-rotate-45 {
  transform: rotate(-45deg);
}
</style>